import { useSongListStore } from './modules/songList'
import { playMessage, songOfList } from '@/api/model/song'
import { reqMusicDetail, reqMusicUrl } from '@/api/song'

import { defineStore } from 'pinia'

const songlistStore = useSongListStore()
function setSongMes(key: string, val: playMessage | songOfList | number) {
  return localStorage.setItem(key, JSON.stringify(val))
}
function getSongMes(key: string) {
  return JSON.parse(localStorage.getItem(key) as string)
}
let curSong = getSongMes('curSong') || undefined
let playMes = getSongMes('playMessage') || undefined
let sid = getSongMes('id') || undefined

export const useSongStore = defineStore({
  id: 'Song',
  state: (): { playMessage: playMessage; curSong: songOfList; id: number } =>
    curSong && playMes
      ? { playMessage: playMes, curSong, id: sid }
      : {
          //当前歌曲信息
          playMessage: {
            url: '',
            time: 0,
            size: 0,
            id: 0,
          },
          id: 0,
          curSong: {
            mv: 0,
            name: '',
            cd: 0,
            id: 0,
            al: { id: 0, name: '', picUrl: '' },
            ar: {
              alias: '',
              id: 0,
              name: '',
            },
          },
        },

  actions: {
    async getSong(id: number) {
      const { songs } = await reqMusicDetail(id)
      console.log('songmessage')

      //console.log(data)
      this.curSong.al = songs[0].al
      this.id = id
      this.curSong.ar = songs[0].ar
      this.curSong.cd = songs[0].cd
      this.curSong.name = songs[0].name
      this.curSong.mv = songs[0].mv
      songlistStore.addSong(songs[0])

      setSongMes('curSong', songs[0])
    },
    async getSongUrl(id: number) {
      const { data } = await reqMusicUrl(id)
      console.log('URL')
      // console.log(data)
      this.id = id

      this.playMessage.url = data[0].url
      this.playMessage.size = data[0].size
      this.playMessage.time = data[0].time

      setSongMes('playMessage', data[0])
    },

    //调用这个方法就可以设置当前播放歌曲
    setId(id: number) {
      this.id = id
      setSongMes('id', id)
      this.getSong(id)
      this.getSongUrl(id)
    },
  },
})
